<?php

namespace app\api\service;

use think\Controller;
use think\Db;
use think\Exception;

class PatternMaster extends Controller {

    /**
     * 获取量体师首頁数据
     * @param $param
     * @return array
     */
    public static function get_pattern_master_index_info($param) {
        try {
            $pattern_master = model('pattern_master')->alias('pm')
                ->field('pm.*, e.region_name r_area')
                ->join('yybs_region e', 'e.region_id = pm.area')
                ->where('member_id', $param['member_id'])->find();

            if ($pattern_master) {
                // 返回数据
                $data['id'] = $pattern_master['id'];
                $data['status'] = $pattern_master['status'];
                $data['audit_msg'] = $pattern_master['audit_msg'];
                $data['nickname'] = $data['nickname'] = $pattern_master->patternMasterMember->memberRoleInfo->nickname; // 昵称
                $data['headimgurl'] = $pattern_master->patternMasterMember->memberRoleInfo->headimgurl ? get_img_url($pattern_master->patternMasterMember->memberRoleInfo->headimgurl) : '';  // 头像

                // 訂單信息
                $dqd = model('order')->all( function($query) use($pattern_master){
                    $query->where(['area' => $pattern_master['r_area'], 'pattern_master_id' => 0, 'status' => 2])->order('id', 'desc');
                });
                $dqd_array = [];
                foreach ($dqd as $v) {
                    $dqd_array[] = [
                        'id' => $v->id,
                        'nickname' => $v->orderMember->memberRoleInfo->nickname,
                        'headimgurl' => get_img_url($v->orderMember->memberRoleInfo->headimgurl),
                        'product_name' => $v->orderProduct->name,
                        'product_img' => $v->orderProduct->thumb,
                        'product_num' => $v->orderProduct->num,
                        'order_sn' => $v->order_sn,
                        'order_price' => $v->price,
                        'mobile' => $v->mobile,
                        'consignee' => $v->consignee,
                        'province' => $v->province,
                        'city' => $v->city,
                        'area' => $v->area,
                        'address' => $v->address,
                        'lat' => $v->lat,
                        'lng' => $v->lng
                    ];
                }

                $data['dqd'] = $dqd_array; // 待抢单
            } else {
                $data = [];
            }

            return api_return(200, $data);
        } catch (\Exception $e) {
            return api_return(0, [], $e->getMessage());
        }
    }

    /**
     * 获取量体师数据
     * @param $param
     * @return array
     */
    public static function get_pattern_master_info($param) {
        try {
            $data = model('pattern_master')->alias('pm')
                ->field('pm.*, p.region_name r_province, c.region_name r_city, e.region_name r_area')
                ->join('yybs_region p', 'p.region_id = pm.province')
                ->join('yybs_region c', 'c.region_id = pm.city')
                ->join('yybs_region e', 'e.region_id = pm.area')
                ->where('member_id', $param['member_id'])->find();

            return api_return(200, $data);
        } catch (\Exception $e) {
            return api_return(0, [], $e->getMessage());
        }
    }

    /**
     * 保存量体师申请信息
     * @param $param
     * @return array
     */
    public static function save_pattern_master($param) {
        try {
            $id = $param['id'];
            $member_id = $param['member_id'];

            $data = [
                'name' => $param['name'],
                'mobile' => $param['mobile'],
                'address' => $param['address'],
                'sex' => $param['sex'],
                'is_experience' => $param['is_experience']
            ];
            isset($param['province']) ? $data['province'] = $param['province'] : $a = 1;
            isset($param['city']) ? $data['city'] = $param['city'] : $a = 1;
            isset($param['area']) ? $data['area'] = $param['area'] : $a = 1;

            if ($id > 0) {
                model('pattern_master')->save($data, ['id' => $id, 'member_id' => $member_id]);
            } else {
                // 先检查用户是否已经申请量体师
                $pattern_master = model('pattern_master')->get(['member_id' => $member_id]);
                if ($pattern_master) {
                    throw new \Exception('请勿重复申请');
                }
                // 添加量体师记录
                $data['member_id'] = $member_id;
                model('pattern_master')->save($data);
            }
            return api_return(200, []);
        } catch (\Exception $e) {
            return api_return(0, [], $e->getMessage());
        }
    }

    /**
     * 新订单通知
     * @param $param
     * @return array
     */
    public static function inform($param) {
        try {
            file_put_contents('inform.txt', '开始通知' . " \n ");
            // 获取订单信息
            $order = model('order')->get(['id' => $param['order_id']]);
            file_put_contents('inform.txt', json_encode($order) . "---订单 \n ", FILE_APPEND);
            // 根据订单收获地址  获取市、区 对应的ID   （地址名称有重复   通过市、区一起来选择对应的量体师）
            $city = model('region')->get(['region_name' => $order['city']]);
            $area = model('region')->get(['region_name' => $order['area'], 'parent_id' => $city['region_id']]);
            // 查询量体师
            $pattern_master_s = model('pattern_master')->all(['area' => $area->region_id, 'status' => 2]);
            file_put_contents('inform.txt', json_encode($pattern_master_s) . "---量体师 \n ", FILE_APPEND);
            foreach ($pattern_master_s as $v) {
                file_put_contents('inform.txt',  "---量体师-------- \n ", FILE_APPEND);
                $mobile = $v->patternMasterMember->username;
                $openid = $v->patternMasterMember->openid;
                file_put_contents('inform.txt',  $mobile  . '--' . $openid .  "---量体师-------- \n ", FILE_APPEND);
                $address = $order->province . $order->city . $order->area . $order->address;
                $param = [
                    'mobile' => $mobile,
                    'type' => 2,
                    'order_sn' => $order->order_sn,
                    'address' => $address,
                    'linkman' => $order->consignee,
                    'address_mobile' => $order->mobile
                ];
                file_put_contents('inform.txt', json_encode($param) . "---量体师 \n ", FILE_APPEND);
                \app\api\service\NoteCode::send_code($param);

                /* +  -----    订单生成成功，发送微信模板消息通知  ----- + */
                if ($openid) {
                    $param = [
                        'touser' => $openid,
                        'template_id' => '-wjkS0vN_NOaiYY6biMRlySepDiPxzUu3TfcFb5FQnk',
                        'url' => request()->domain() . url('pattern_master/info', ['id' => $order->id]),
                        'data' => [
                            'first' => [ 'value' => '发现新订单', 'color' => '#173177'],
                            'keyword1' => [ 'value' => $order->order_sn, 'color' => '#173177'],
                            'keyword2' => [ 'value' => date('Y-m-d H:i:s', $order->create_time), 'color' => '#173177'],
                            'remark' => [ 'value' => "请尽快处理 \n 订制人：" . $order->consignee . " \n 联系电话：" . $order->mobile . " \n 收货地址：" . $address, 'color' => '#173177'],
                        ]
                    ];
                    file_put_contents('inform.txt', json_encode($param) . "---量体师 \n ", FILE_APPEND);
                    send_create_order_wechat_tmplmsg(json_encode($param));
                }
            }
            return api_return(200, []);
        } catch (\Exception $e) {
            return api_return(0, [], $e->getMessage());
        }
    }
}
